package com.qf.hospital.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.constants.HospitalConstants;
import com.qf.hospital.entity.SysMenu;
import com.qf.hospital.entity.SysRole;
import com.qf.hospital.entity.SysUser;
import com.qf.hospital.entity.SysUserExample;
import com.qf.hospital.enums.HospitalExceptionEnums;
import com.qf.hospital.exception.HospitalException;
import com.qf.hospital.mapper.SysUserMapper;
import com.qf.hospital.realm.HospitalRealm;
import com.qf.hospital.service.SysRoleService;
import com.qf.hospital.service.SysUserService;
import com.qf.hospital.util.ExampleUtil;
import com.qf.hospital.vo.SideVO;
import com.qf.hospital.vo.UserRoleVO;
import javafx.geometry.Side;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zjw
 * @description
 * @date 2021/10/15 11:43
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    private final String INIT_PASSWORD = "123456789abc!";

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 根据用户名查询用户信息
     * @param loginName
     * @return
     */
    @Override
    public SysUser findByLoginName(String loginName) {
        //1. 准备example设置条件
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        //2. 设置查询条件
        criteria.andLoginNameEqualTo(loginName);
        //3. 执行查询
        List<SysUser> list = sysUserMapper.selectByExample(example);
        //4. 返回
        if(list != null && list.size() == 1){
            SysUser sysUser = list.get(0);
            if(sysUser.getAvailable() == 0){
                // 用户已经失效
                log.info("【登录功能】 用户已经失效，请联系管理员！");
                throw new HospitalException(HospitalExceptionEnums.USER_HAS_EXPIRED);
            }
            return sysUser;
        }
        return null;
    }


    /**
     * 根据用户id查询菜单信息
     * @param userId
     * @return
     */
    @Override
    public List<SideVO> findSideByUserId(Integer userId) {
        //1. 根据userId查询菜单信息
        List<SysMenu> sysMenuList = sysUserMapper.findMenuByUserId(userId);

        //2. 封装数据
        List<SideVO> result = new ArrayList<>();
        Map<Integer,SideVO> oneLevelMenu = new HashMap<>();
        //2.1 从sysMenuList筛选出所有parentId = 1的以及菜单，并且封装到List集合
        ListIterator<SysMenu> menuListIterator = sysMenuList.listIterator();
        while(menuListIterator.hasNext()){
            SysMenu sysMenu = menuListIterator.next();
            if(sysMenu.getParentId() == 1){
                // 一级菜单
                SideVO vo = new SideVO();
                BeanUtils.copyProperties(sysMenu,vo);
                oneLevelMenu.put(vo.getId(),vo);
                menuListIterator.remove();
            }
        }
        //2.2 从sysMenuList中找到二级菜单，并且将二级菜单封装到指定的一级菜单的children属性中
        for (SysMenu sysMenu : sysMenuList) {
            SideVO parentSideVO = oneLevelMenu.get(sysMenu.getParentId());
            if(parentSideVO != null){
                // 二级菜单找到了指定的一级菜单
                SideVO childSideVO = new SideVO();
                BeanUtils.copyProperties(sysMenu,childSideVO);
                parentSideVO.getChildren().add(childSideVO);
            }
        }
        //2.3 将Map集合中的数据，都封装到result的list集合中
        for (Map.Entry<Integer, SideVO> integerSideVOEntry : oneLevelMenu.entrySet()) {
            result.add(integerSideVOEntry.getValue());
        }

        //3. 返回
        return result;
    }

    @Override
    public PageInfo<SysUser> selectAllUser(String realname, String loginname, String address, String phone, String identity, Integer page, Integer limit) {
        //1. 执行分页
        PageHelper.startPage(page,limit);

        //2. 封装查询条件
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        //2.1 真实姓名
        if(!StringUtils.isEmpty(realname)){
            criteria.andRealNameLike(ExampleUtil.any(realname));
        }
        //2.2 登录名
        if(!StringUtils.isEmpty(loginname)){
            criteria.andLoginNameLike(ExampleUtil.any(loginname));
        }
        //2.3 地址
        if(!StringUtils.isEmpty(address)){
            criteria.andAddressLike(ExampleUtil.any(address));
        }
        //2.4 手机号
        if(!StringUtils.isEmpty(phone)){
            criteria.andPhoneLike(ExampleUtil.any(phone));
        }
        //2.5 手机号
        if(!StringUtils.isEmpty(identity)){
            criteria.andIdentityLike(ExampleUtil.any(identity));
        }

        //3. 执行查询
        List<SysUser> list = sysUserMapper.selectByExample(example);

        //4. 封装PageInfo
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);

        //5. 返回
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addUser(SysUser sysUser) {
        //1. 封装数据 pwd，salt，type（默认值为2，系统用户）
        //1.1 生成盐
        String salt = UUID.randomUUID().toString();
        //1.2 生成密码
        String pwd = new Md5Hash(INIT_PASSWORD,salt,HospitalRealm.HASH_ITERATIONS).toString();
        //1.3 生成用户类型
        Integer type = HospitalConstants.USER_TYPE_SYSTEM;
        //1.4 设置到sysUser中
        sysUser.setSalt(salt);
        sysUser.setPwd(pwd);
        sysUser.setType(type);

        //2. 执行添加
        int count = sysUserMapper.insertSelective(sysUser);

        //3. 健壮性判断
        if(count != 1){
            log.error("【添加用户信息】 添加失败！ sysUser = {}",sysUser);
            throw new HospitalException(HospitalExceptionEnums.USER_ADD_ERROR);
        }

    }

    @Override
    public List<UserRoleVO> initUserRole(Integer userid) {
        //1. 查询全部角色信息
        List<SysRole> sysRoleList = sysRoleService.findAll();

        //2. 查询当前用户拥有的角色id
        List<Integer> userRoleId = sysUserMapper.findUserRoleIdByUserId(userid);

        //3. 根据上述结果，封装UserRoleVO
        List<UserRoleVO> data = new ArrayList<>();
        for (SysRole sysRole : sysRoleList) {
            UserRoleVO vo = new UserRoleVO();
            BeanUtils.copyProperties(sysRole,vo);
            if(userRoleId.contains(vo.getRoleId())){
                vo.setLayChecked(true);
            }
            data.add(vo);
        }

        //4. 返回
        return data;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveUserRole(Integer userid, Integer[] ids) {
        //1. 先删除
        sysUserMapper.deleteUserRoleByUserId(userid);

        //2. 再添加
        if(ids != null && ids.length > 0){
            int count = sysUserMapper.saveUserRole(userid,ids);
            if(count != ids.length){
                log.error("【分配角色信息】 分配角色信息失败！ userId = {}，roleIds = {}",userid,Arrays.toString(ids));
                throw new HospitalException(HospitalExceptionEnums.USER_SAVE_USER_ROLE_ERROR);
            }
        }
    }


}
